package com.swak.persistence.mybatis.methods.impls;

import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.AbstractMethod;
import com.swak.persistence.mybatis.methods.Sqls;
import com.swak.utils.StringUtils;

@Deprecated
public class Statistics extends AbstractMethod {

	@Override
	protected void doInject() {
		if (!this.table.define.useStat()) {
			return;
		}
		String sql = new StringBuilder().append(SCRIPT_START).append(INSERT).append(SPACE).append(this.table.getName())
				.append(LEFT_BRACKET).append(this.parseSqlColumns()).append(RIGHT_BRACKET).append(SPACE).append(VALUES)
				.append(LEFT_BRACKET).append(this.parseInsertSqlProperty()).append(RIGHT_BRACKET).append(SPACE)
				.append(REPLACE).append(SPACE).append(UPDATE).append(SPACE).append(this.parseUpdateProperty())
				.append(PADDING2).append(SCRIPT_END).toString();

		this.addInsertMappedStatement(this.table.entity, Sqls.STATISTIC.getMethod(), sql);
	}

	/**
	 * 解析修改列
	 */
	protected String parseUpdateProperty() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : this.table.columns) {
			String name = column.name;
			String property = column.javaProperty;
			if (!column.isPk() && !column.isCreateDate() && column.isStat()) {// +1 操作，后期可以支持减少操作
				sql.append("<if test=\"").append(property).append(" != null\">").append(name).append(EQUALS)
						.append(StringUtils.format(STAT_CHECK, name, name)).append(PLUS).append(HASH_LEFT_BRACE)
						.append(property).append(RIGHT_BRACE).append(SPLIT).append("</if>");
			} else if (!column.isPk() && !column.isCreateDate()) { // 可以修改
				sql.append("<if test=\"").append(property).append(" != null\">").append(name).append(EQUALS)
						.append(HASH_LEFT_BRACE).append(property).append(RIGHT_BRACE).append(SPLIT).append("</if>");
			}
		}
		return sql.toString();
	}

	/**
	 * insert 后面的属性值
	 * 
	 * @param <T>
	 * @param table
	 * @return
	 */
	protected String parseInsertSqlProperty() {
		return this.parseInsertSqlPropertyWithPrex(StringUtils.EMPTY);
	}

	/**
	 * insert 后面的属性值
	 * 
	 * @param <T>
	 * @param table
	 * @return
	 */
	protected String parseInsertSqlPropertyWithPrex(String prex) {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : table.columns) {
			String name = column.javaProperty;
			sql.append(HASH_LEFT_BRACE).append(StringUtils.isNotBlank(prex) ? prex + DOT : StringUtils.EMPTY)
					.append(name).append(RIGHT_BRACE).append(SPLIT);
		}
		if (table.hasColumn()) {
			sql.delete(sql.lastIndexOf(SPLIT), sql.length() - 1);
		}
		return sql.toString();
	}
}
